import React, {useRef, useState} from 'react';
import {View, ScrollView} from 'react-native';
import {useTranslation} from 'react-i18next';
import {userApi} from '@/services/api/userApi';
import {useMMKVObject} from '@/hooks/useMMkv';
import {useForm, Controller} from 'react-hook-form';
import Toast from '@/utils/toast';
import {ErrorText} from '@/components/ErrorText';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {TextInput, CodeTextInput, Button} from 'tsun-smart-ui';

interface UserInfo {
  email?: string;
  // ... 其他用户信息字段
}

interface FormData {
  email: string;
  verificationCode: string;
}

const ChangeEmailScreen = ({
  navigation,
}: ReactNavigation.RootStackScreenProps<'ChangeEmail'>) => {
  const {t} = useTranslation();
  const [userInfo] = useMMKVObject<UserInfo>('user_info');
  const {bottom} = useSafeAreaInsets();
  const [loading, setLoading] = useState(false);
  const btnRef = useRef<{
    setTargetDate: (date: number) => void;
  }>(null);
  const {
    control,
    handleSubmit,
    formState: {errors},
    trigger,
    getValues,
  } = useForm<FormData>({
    defaultValues: {
      email: '',
      verificationCode: '',
    },
  });

  // 发送验证码
  const handleSendCode = async () => {
    const isValid = await trigger('email');
    if (!isValid) return;
    try {
      setLoading(true);
      btnRef.current?.setTargetDate(Date.now() + 3 * 60 * 1000);
      const {email} = getValues();
      await userApi.sendChangeCode(email);
      Toast.success({
        message: t('common.mail.code.send', {defaultValue: '验证码已发送'}),
      });
    } catch {
      btnRef.current?.setTargetDate(void 0);
    } finally {
      setLoading(false);
    }
  };

  // 提交修改
  const onSubmit = async (data: FormData) => {
    try {
      setLoading(true);
      await userApi.changeEmail({
        email: data.email.trim(),
        code: data.verificationCode.trim(),
      });
      Toast.success({
        message: t('common.updateSuccess', {defaultValue: '修改成功'}),
      });
      // 更新成功后返回
      navigation.goBack();
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView contentContainerClassName="flex-1">
      <View className="p-4 flex-1 justify-between">
        <View>
          {/* 新邮箱输入 */}
          <View>
            <Controller
              name="email"
              control={control}
              rules={{
                required: t('table.inputemailTip', {
                  defaultValue: '请输入邮箱',
                }),
                pattern: {
                  value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                  message: t('mail.vail.tips', {
                    defaultValue: '请输入有效的邮箱地址',
                  }),
                },
                validate(value) {
                  if (value === userInfo?.email) {
                    return Promise.resolve(t('userSetting.email.text'));
                  }
                  return true;
                },
              }}
              render={({field: {onChange, value}}) => (
                <TextInput
                  label={t('table.email', {defaultValue: '邮箱'})}
                  left="email"
                  placeholder={t('table.inputemailTip', {
                    defaultValue: '请输入邮箱',
                  })}
                  value={value}
                  onChangeText={onChange}
                  keyboardType="email-address"
                  autoCapitalize="none"
                />
              )}
            />
            <View className="py-2 ml-14">
              {errors.email && <ErrorText text={errors.email.message!} />}
            </View>
          </View>

          {/* 验证码输入 */}
          <View>
            <Controller
              name="verificationCode"
              control={control}
              rules={{
                required: t('password.accountPlaceholder3', {
                  defaultValue: '请输入验证码',
                }),
              }}
              render={({field: {onChange, value}}) => (
                <CodeTextInput
                  maxLength={6}
                  left="Safety"
                  placeholder={t('password.accountPlaceholder3', {
                    defaultValue: '请输入验证码',
                  })}
                  value={value}
                  buttonStyle={{
                    borderRadius: 6,
                  }}
                  onChangeText={onChange}
                  keyboardType="number-pad"
                  autoCapitalize="none"
                  i18n={{
                    sendText: t('common.code.send', {
                      defaultValue: '发送验证码',
                    }),
                    resendTemplate: '{seconds}',
                  }}
                  onPress={handleSendCode}
                  btnRef={btnRef}
                />
              )}
            />
            <View className="pt-2 ml-14">
              {errors.verificationCode && (
                <ErrorText text={errors.verificationCode.message!} />
              )}
            </View>
          </View>
        </View>

        {/* 提交按钮 */}
        <View
          style={{
            paddingBottom: bottom || 27,
          }}>
          <Button
            loading={loading}
            disabled={loading}
            onPress={handleSubmit(onSubmit)}
            title={t('dytable.submit', {defaultValue: '确定'})}></Button>
        </View>
      </View>
    </ScrollView>
  );
};

export default ChangeEmailScreen;
